using ECommerce.Web.NHibernate.Sessions;
using ECommerce.Web.Services.ShoppingSessions;
using ECommerce.Web.ViewModels;
using NHibernate;
using NHibernate.Criterion;
using System;

namespace ECommerce.Web.ViewQueries
{
    public interface IBasketViewQuery
    {
        BasketView GetQuery();
    }

    public class BasketViewQuery : IBasketViewQuery
    {
        private readonly IShoppingSession shoppingSession;

        public BasketViewQuery(IShoppingSession shoppingSession)
        {
            this.shoppingSession = shoppingSession;
        }

        public BasketView GetQuery()
        {
            Guid shopperToken = this.shoppingSession.GetShopperToken();

            ISession session = SessionSource.Current.GetSession();

            var criteria = session.CreateCriteria<BasketView>();

            criteria.Add(Expression.Eq("ShopperId", shopperToken));

            var view = criteria.UniqueResult<BasketView>();

            if (view == null)
            {
                view = new BasketView();
            }

            return view;
        }
    }
}